/* eslint-disable react/jsx-key */
import moment from 'moment';
import React, { useState, useRef } from 'react';
import { Popconfirm, Tooltip, Modal, message } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import Uploadcom from './uploadcom';
import { connect } from 'umi';
import { PlusOutlined, ImportOutlined, ExportOutlined, FileExcelFilled } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import { getFetch, postFetch } from '@/utils/doFetch';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
    company_name: {
      value: null,
      type: 'input',
      title: '公司名称',
      width: 260,
      name: ['company_name'],
      required: true,
      linked: true,
    },
    customer_name: {
      value: null,
      type: 'input',
      title: '联系人',
      name: ['customer_name'],
      required: true,
      linked: true,
    },
    customer_phone: {
      value: null,
      type: 'input',
      title: '联系方式',
      name: ['customer_phone'],
      required: true,
      linked: true,
    },
    address: {
      value: null,
      type: 'input',
      title: '注册地址',
      name: ['address'],
      required: true,
      linked: true,
    },
    register_time: {
      value: null,
      type: 'datepicker',
      title: '成立日期',
      name: ['register_time'],
      required: true,
      linked: true,
      disabledDate: (current) => {
        return current && current > moment().endOf('day');
      },
    },
  },
  valueEnum = {
    // stalled       初始状态         not_remark    未标记         not_through   未打通         latent        潜在         wechat        加微信         intention     有意向
    stalled: {
      text: '名录中',
    },
    not_remark: {
      text: '未标记',
    },
    not_through: {
      text: '未打通',
    },
    latent: {
      text: '潜在',
    },
    wechat: {
      text: '加微信',
    },
    intention: {
      text: '有意向',
    },
  };

function Directories(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [vis, cvis] = useState(false),
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    {
      location: { query },
      dispatch,
    } = props;

  let actionRef = useRef(),
    ChildRef = null;

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
          reload={reload}
        />
      ),

    },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '注册地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
    },
    {
      title: '成立日期',
      dataIndex: 'register_time',
      key: 'register_time',
      search: false,
      render: (text, row) => {
        return row?.register_time ? moment(row.register_time).format('YYYY-MM-DD') : '-';
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      hideInTable: true,
      search: false,
      render: (text, row) => <span>{valueEnum[row.status]?.text}</span>,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      render: (text, record, _, action) => [
        <Popconfirm
          title="确认认领该企业名录？"
          onConfirm={() => {
            dispatch({
              type: 'business/claim',
              payload: { id: record.id },
            }).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
                cvs(false);
              }
            });
          }}
        >
          <a>认领</a>
        </Popconfirm>,
        <a
          onClick={() => {
            ciftype({
              val: 'edit',
              id: record.id,
              title: '修改',
            });
            cf(() => {
              for (let i in defaultFields) {
                defaultFields[i].value = record[i];
              }
              return { ...defaultFields };
            });
            cvs(true);
          }}
        >
          修改
        </a>,
        <Popconfirm
          title="确认删除该企业名录？"
          onConfirm={() => {
            dispatch({
              type: 'business/deletedirectory',
              payload: record.id,
            }).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
                cvs(false);
              }
            });
          }}
        >
          <a style={{ color: 'red' }}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  let extrarender = [
    <Tooltip title="新增企业名录">
      <div
        className="action"
        onClick={() => {
          cvs(true);
          cf((fields) => {
            for (let i in fields) {
              fields[i].value = null;
            }
            return { ...fields };
          });
          ciftype({
            val: 'add',
            title: '新增企业名录',
          });
        }}
      >
        <PlusOutlined />
      </div>
    </Tooltip>,
    <Tooltip title="导入企业名录">
      <div
        className="action"
        style={{ margin: '0 12px' }}
        onClick={() => {
          cvs(true);
          ciftype({
            val: 'inside',
            title: '导入企业名录',
          });
        }}
      >
        <ImportOutlined rotate={-90} />
      </div>
    </Tooltip>,
    <Tooltip title="导出企业名录">
      <div
        className="action"
        onClick={() => {
          const hide = message.loading('正在导出..', 0);
          postFetch({ url: '/wbn-api/directory/batch_export', params: {} }).then((res) => {
            window.open(res?.data);
            hide();
          });
        }}
      >
        <ExportOutlined rotate={-90} />
      </div>
    </Tooltip>,
    <Tooltip title="获取导入模板">
      <div
        className="action"
        style={{ margin: '0 0 0 12px' }}
        onClick={() => {
          getFetch({ url: '/wbn-api/directory/export_template', params: {} }).then((res) => {
            window.open(res?.data);
          });
        }}
      >
        <FileExcelFilled />
      </div>
    </Tooltip>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'business/directory',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type: 'business/editdirectory',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/directory"
        extraparams={{ is_myself: 0 }}
        childposition="top"
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
       />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        {iftype.val == 'see' && iftype.curitem ? (
          <ProDescriptions
            title={`企业名录的详细信息`}
            columns={[...columns]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : iftype.val == 'inside' ? (
          <div>
            <Uploadcom
              reload={() => {
                reload();
                cvs(false);
              }}
             />
          </div>
        ) : (
          <InitForm
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={
              props.loading.effects['business/cashierretry'] ||
              props.loading.effects['business/addpaymentorder'] ||
              !vs
            }
            halfsave={false}
           />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ business, loading }) => ({
  business,
  loading,
}))(Directories);
